import fetch from '@/utils/fetch'
import MockAdapter from 'axios-mock-adapter'
import Mock from 'mockjs'
import moment from 'moment'

import { LoginUsers, Users } from './data/user'

export default {
  /**
   * mock bootstrap 该需要函数在main.js中初始化启动
   */
  bootstrap() {
    // 此处很重要，需要传入我们自己封装了axios实例对象 全局延迟500豪秒
    let mock = new MockAdapter(fetch, { delayResponse: 500 })

    // 登录相关
    mock.onPost('/login').reply(200, { code: 0, token: Mock.Random.guid() })
    mock.onPost('/logout').reply(200, { code: 0, success: true })
    mock.onPost('/info').reply(200, { code: 0, data: LoginUsers })

    // 用户列表相关CRUD模拟
    let _Users = Users

    // 获取用户列表（分页）
    mock.onGet('/user/list').reply(config => {
      // es6参数解构
      let { currentPage, pageSize, name, region, range } = config.params
      // 先执行查询过滤再分页
      let _QUsers = _Users
      // 过滤姓名（模糊）
      if (name && name !== '') {
        _QUsers = _QUsers.filter(u => u.name.includes(name))
      }
      // 过滤区域
      if (region && region !== '') {
        _QUsers = _QUsers.filter(u => u.region === region)
      }
      // 过滤日期范围
      if (range && range !== '') {
        _QUsers = _QUsers.filter(u => moment(u.birth).isBetween(...range))
      }
      let totalCount = _QUsers.length
      let pagedUsers = _QUsers.filter(
        (u, index) =>
          index < pageSize * currentPage &&
          index >= pageSize * (currentPage - 1)
      )
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve([
            200,
            {
              code: 0,
              totalCount: totalCount,
              users: pagedUsers
            }
          ])
        }, 100)
      })
    })

    // 删除用户
    mock.onPost('/user/del').reply(config => {
      let { id } = config.params
      _Users = _Users.filter(u => u.id !== id)
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve([
            200,
            {
              code: 0,
              msg: '删除成功'
            }
          ])
        }, 100)
      })
    })

    // 批量删除用户
    mock.onPost('/user/batchdel').reply(config => {
      let { ids } = config.params
      ids = ids.split(',')
      _Users = _Users.filter(u => !ids.includes(u.id.toString())) // 此处注意数组元素类型需要转换
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve([
            200,
            {
              code: 0,
              msg: '删除成功'
            }
          ])
        }, 500)
      })
    })

    // 新增/编辑用户 区别在于id是否为空
    mock.onPost('/user/save').reply(config => {
      let {
        id,
        name,
        email,
        region,
        zip,
        addr,
        education,
        birth,
        sex
      } = config.params
      let msg = ''
      if (!id) {
        _Users.push({
          id: Mock.Random.integer(100, 1000), // 随机给一个整形数字ID
          name: name,
          email: email,
          zip: zip,
          region: region,
          addr: addr,
          education: education,
          birth: birth,
          sex: sex
        })
        msg = '新增纪录成功'
      } else {
        _Users.some(u => {
          if (u.id === id) {
            u.name = name
            u.addr = addr
            u.region = region
            u.email = email
            u.zip = zip
            u.education = education
            u.birth = birth
            u.sex = sex
            return true
          }
        })
        msg = '编辑纪录成功'
      }
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve([
            200,
            {
              code: 0,
              msg: msg
            }
          ])
        }, 1000)
      })
    })
  }
}
